package com.kolon.business.mVolunteer.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import sun.misc.BASE64Encoder;

import com.kolon.framework.constant.Constant;
import com.kolon.framework.interfaces.SimpleController;
import com.kolon.framework.util.ComUtil;
import com.kolon.framework.util.MsgUtil;

@Controller("com.kolon.business.mVolunteer.controller.getXmlController")
public class getXmlController implements SimpleController {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/business/mVolunteer/output.do")
	public ModelAndView controller(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
		
		// 도메인
		ModelAndView modelAndView = new ModelAndView();
		
		//버튼 카운트
		int num = 0;
		
		if(request.getParameter("num") == null || "".equals(request.getParameter("num"))){
			
		}else{
			num = Integer.parseInt(request.getParameter("num"));
		}
		
		//System.out.println("num :::: "+num);
		String selectedYear = "";
		String ayear = "";
		String amonth = "";
		
		if(request.getParameter("selectedYear") == null || "".equals(request.getParameter("selectedYear"))){
			
			ayear = getDefaultYear();
			amonth = getDefaultMonth();
			
			//System.out.println("ayear =="+ayear+": amonth=="+amonth);
		}else{
			selectedYear = request.getParameter("selectedYear");
			ayear = selectedYear.substring(0, 4);
			amonth = selectedYear.substring(5, 7);
			
			//System.out.println("selected Year : "+selectedYear);
			//System.out.println("in else month : "+amonth);
		}
		//System.out.println("year : "+ayear);
		//System.out.println("month : "+amonth);
		String param_yearmonth = getYearMonth(Integer.parseInt(ayear), Integer.parseInt(amonth), num);
		
		//System.out.println("param_yearmonth :"+param_yearmonth);
		//System.out.println("Year!!!! : "+param_yearmonth);
		// 포멧변환
		SimpleDateFormat form = new SimpleDateFormat("yyyyMMdd");
		Date date = form.parse(param_yearmonth+"01");
		SimpleDateFormat form1 = new SimpleDateFormat("yyyy.MM");
		String dateString = form1.format(date);
		//System.out.println("dateString : "+dateString);
	
		//String url = "http://203.225.255.126:8181/kolon/lcm/CarMob/PM_CarMob_R01.jsp?KenID=happyrecs&YM="+param_yearmonth;
		String url = "http://appif.kolon.com";//MsgUtil.getMessage("xml.url");
		
		// 세션
		HttpSession httpSession = request.getSession();
		Map userMap = (Map)httpSession.getAttribute(Constant.SESSION_USER_INFO);
		String id = (String)userMap.get("userId");
		String pw = (String)userMap.get("userPw");
		String busoCode = (String)userMap.get("DeptCode");
		//String CompanyCode = (String)userMap.get("CompanyCD");
		String type = ComUtil.nullChk(request.getParameter("type"), "KOLONCOM");
		String page = ComUtil.nullChk(request.getParameter("page"), "1");
		int pageInt = ComUtil.sToi(page) * 15;
		
		//System.out.println("type :"+type);
		
		/*
		String CompanyCode = "";
		if("AFF".equals(type)) {
			CompanyCode = (String)userMap.get("CompanyCD");
		}else{
			CompanyCode = "BNT";
		}
		*/
		
		 String CompanyCode = "";
		if("".equals((String)userMap.get("CompanyCD"))) {
			CompanyCode = "LS";
		}else{
			CompanyCode = (String)userMap.get("CompanyCD");
		}
		 
		//http://appif.kolon.com/contribute.aspx?Gubun=1&CompanyCode=LS&YMD=201205
		StringBuffer buffer = new StringBuffer();
		buffer.append(url); 
		buffer.append("/Contribute.aspx?Gubun=1");
		//buffer.append("&companyCode=").append("BNT");
		buffer.append("&companyCode=").append(CompanyCode);
		//buffer.append("&busoCode=").append(busoCode);
		buffer.append("&YMD=").append(param_yearmonth);
		//buffer.append("&userid=").append(id);
		//buffer.append("&pw=").append(pw);
		
		System.out.println("url toString : "+buffer.toString());
		// XML DOCUMENT 및 인증 처리
		//Document doc = ComUtil.getDocument(buffer.toString(), id, pw);
		
		Document doc2 = ComUtil.getDocument(buffer.toString(), id, pw);
		Element element2 = doc2.getRootElement();
		List xmlList2 = element2.getChildren("Table");
		
		List mapList2 ;
		Iterator itXml2;
		//System.out.println("4");
		if(xmlList2 != null){
			mapList2 = new ArrayList();
		 itXml2 = xmlList2.iterator();
		 //System.out.println("4-1");
			// XML 데이터 
			while (itXml2.hasNext()) {
			
				Map map = new HashMap();
				Element el = (Element)itXml2.next();
				map.put("SERVICE_DATE", el.getChild("SERVICE_DATE").getText());
				map.put("SERVICE_START_TIME", el.getChild("SERVICE_START_TIME").getText());
				map.put("SERVICE_END_TIME", el.getChild("SERVICE_END_TIME").getText());
				map.put("SERVICE_CODE", el.getChild("SERVICE_CODE").getText());
				map.put("SERVICE_NAME", el.getChild("SERVICE_NAME").getText());
				map.put("POSS_YN", el.getChild("POSS_YN").getText());
				map.put("POSS_NUMBER", el.getChild("POSS_NUMBER").getText());
				//System.out.println("here is :: "+el.getChild("SERVICE_NAME").getText());
				mapList2.add(map);
			}
		}else{
			mapList2 = new ArrayList();
		//System.out.println("4-2");
			//mapList2.add(map);
		}
		//System.out.println("444");
		modelAndView.addObject("mapList2", mapList2);
		modelAndView.addObject("mapList2Size", mapList2.size());
		modelAndView.addObject("yearmonth", dateString);
		modelAndView.setViewName("/business/mVolunteer/output");
		return modelAndView;
	}
	
	// util 클래스를 하나 만들어도 좋고 일단 여기다 적음
	public String getYearMonth(int year, int month, int num){
		//System.out.println("getYearMonth year : "+year);
		//System.out.println("getYearMonth month : "+month);
		//System.out.println("getYearMonth num : "+num);
		int day = 01;
		//System.out.println("month : "+month);//3
		GregorianCalendar cld;
		cld = new GregorianCalendar();
		
		if(num != 0){
			cld.add(Calendar.MONTH, num);
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		return sdf.format(cld.getTime());	
	}
	
	// 현재 년월 가져오기
	public String getDefaultYear(){
		Calendar cl = Calendar.getInstance();
		String dym = String.valueOf(cl.get(Calendar.YEAR));
		return dym;
	}
	// 현재 월 가져오기
	public String getDefaultMonth(){
		Calendar cl = Calendar.getInstance();
		cl.add(Calendar.MONTH, +1);
		String dym = String.valueOf(cl.get(cl.MONTH));
		return dym;
	}
	
	
	public InputStream getDocument(String urlStr, String id, String pw) {
		HttpURLConnection connection = null;

		try {
			URL url = new URL(urlStr);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("GET");
			BASE64Encoder enc = new sun.misc.BASE64Encoder();
			String userpassword = id + ":" + pw;
			String encodedAuthorization = enc.encode( userpassword.getBytes() );
			connection.setRequestProperty("Authorization", "Basic "+encodedAuthorization);
			connection.getResponseCode();
			//System.out.println("ok ? : "+connection.getResponseCode());
			// 커넥션 성공여부를 확인해주고
			return connection.getInputStream();
			// 커넥션으로 딴 인풋스트림을 connection이 들고있는거지
			// 저쪽 소스는
			// 이걸 document로 바꿔서 넘기는거고
			//return new BufferedReader(new InputStreamReader(new URL(url).openStream()))
		} catch (Exception e) {
			return null;
		} finally {
			if(connection != null) {
				connection.disconnect();
			}
		}
	}
}